<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of QuestionController
 *
 * @author tuancasi
 */
class QuestionController extends Controller {

    public function actionIndex() {
	$model = new Question('search');
	$model->unsetAttributes();
	if (isset($_GET['Question'])) {
	    $model->attributes = $_GET['Question'];
	}
	$this->render('index', array('model' => $model));
    }

    public function actionAdd($type = Question::TYPE_GREETING) {
	$model = new Question();
	$model->type = $type;
	if (isset($_POST['Question']) && $_POST['answer']) {
	    $model->attributes = $_POST['Question'];
	    if ($_POST['answer']) {
		$model->list_answer = serialize($_POST['answer']);
	    }
	    if ($model->validate()) {
		$model->save();
		$this->redirect(url('question'));
	    }
	}
	$this->render('add', array('model' => $model, 'type' => $type));
    }

    public function actionUpdate($id) {
	$model = $this->loadModel($id);
	if (isset($_GET['type'])) {
	    $type = $_GET['type'];
	    $model->type = $type;
	} else {
	    $type = $model->type;
	}
	if (isset($_POST['Question'])) {
	    $model->attributes = $_POST['Question'];
	    if (isset($_POST['answer']) && $_POST['answer']) {
		$model->list_answer = serialize($_POST['answer']);
	    }
	    if ($type == Question::TYPE_GREETING) {
		$model->list_answer = '';
	    }
	    if ($model->validate()) {
		$model->save();
		$this->redirect(url('question'));
	    }
	}
	$this->render('update', array('model' => $model, 'type' => $type));
    }

    public function actionDelete($id) {
	$model = $this->loadModel($id);
	$model->delete();
    }

    private function loadModel($id) {
	$model = Question::model()->findByPk($id);
	if ($model) {
	    return $model;
	} else {
	    throw new CHttpException(400, 'The page was not found');
	}
    }

}

